<?php
// 应用公共文件
if (!function_exists('returnFormat')) {
    /**
     * 格式化输出返回值
     * @param int $code
     * @param string $msg
     * @param array $data
     * @return mixed
     */
    function returnFormat($code = 0, $msg = "", $data = [])
    {
        $res['code'] = $code;
        $res['data'] = $data;
        $res['msg'] = $msg;
        return $res;
    }
}

if (!function_exists('isBase64')) {
    /**
     * 判断字符串是不是base64编码
     * base64_decode：解码
     * base64_encode：再次编码
     */

    function isBase64($s)
    {
        // Check if there are valid base64 characters
        if (!preg_match('/^[a-zA-Z0-9\\/\\+]*={0,2}$/', $s)) return false;

        // Decode the string in strict mode and check the results
        $decoded = base64_decode($s, true);
        if (false === $decoded) return false;

        // if string returned contains not printable chars
        if (0 < preg_match('/((?![[:graph:]])(?!\\s)(?!\\p{L}))./', $decoded, $matched)) return false;

        // Encode the string again
        if (base64_encode($decoded) != $s) return false;

        return true;
    }


}
if (!function_exists('getUrl')) {
    /**
     * 获取当前的访问路径
     * @return [type] [description]
     */
    function getUrl()
    {
        $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
        $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
        $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
        $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self . (isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : $path_info);
        return $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $relate_url;
    }
}
if (!function_exists('getNow')) {
    /**
     * 获取当时时间
     * @param string $fmt 格式化
     * @return false|string
     */
    function getNow($fmt = "Y-m-d H:i:s")
    {
        return date($fmt);
    }
}
if (!function_exists('getNowDate')) {
    /**
     * 获取当时时间
     * @param string $fmt 格式化
     * @return false|string
     */
    function getNowDate($fmt = "Y-m-d")
    {
        return date($fmt);
    }
}

if (!function_exists('getAgeByBirthday')) {
    /**
     * 根据出生日期获取年龄
     * @param string $birthday 出生日期时间戳
     * @return false|string
     */
    function getAgeByBirthday($birthday)
    {
        //格式化出生时间年月日
        $byear = date('Y', $birthday);
        $bmonth = date('m', $birthday);
        $bday = date('d', $birthday);

        //格式化当前时间年月日
        $tyear = date('Y');
        $tmonth = date('m');
        $tday = date('d');

        //计算年龄
        $age = $tyear - $byear;
        if ($bmonth > $tmonth || $bmonth == $tmonth && $bday > $tday) {
            $age--;
        }
        return $age;
    }
}

if (!function_exists('fixedIdCard')) {
    /**
     * 修复身份证格式
     * @param $idcard
     * @return array|string|string[]
     */
    function fixedIdCard($idcard)
    {
        $idcard = str_replace("x", "X", $idcard);
        $idcard = str_replace("×", "X", $idcard);
        $idcard = str_replace("Ⅹ", "X", $idcard);
        $idcard = str_replace("×", "X", $idcard);
        return $idcard;
    }
}

if (!function_exists('regexpMatchIdCard')) {
    /**
     * 校验身份证号码是否合法
     * @param $str
     * @param bool $getBasicInfo 是否提取身份证号码中的基本信息(出生日期/性别)
     * @return mixed
     */
    function regexpMatchIdCard($str, $getBasicInfo = false)
    {
        //校验身份证位数和出生日期部分
        $pattern = "/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/";
        preg_match($pattern, $str, $match);
        $result = $match ? true : false;
        if (!$result) {
            return false;
        }

        //校验前两位是否是所有省份代码
        $province_code = ['11', '12', '13', '14', '15', '21', '22', '23', '31', '32', '33', '34', '35', '36', '37', '41', '42', '43', '44', '45', '46', '50', '51', '52', '53', '54', '61', '62', '63', '64', '65', '71', '81', '82', '91'];
        if (!in_array(substr($str, 0, 2), $province_code)) {
            return false;
        }

        //校验身份证最后一位
        $ahead17_char = substr($str, 0, 17);
        $last_char = substr($str, -1);
        $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); // 前17位的权重
        $c = array(1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2); //模11后的对应校验码
        $t_res = 0;
        for ($i = 0; $i < 17; $i++) {
            $t_res += intval($ahead17_char[$i]) * $factor[$i];
        }
        $calc_last_char = $c[$t_res % 11];
        if ($last_char != $calc_last_char) {
            return false;
        }

        if (!$getBasicInfo) {
            return $result;
        }

        //从身份证号码中提取出生日期和性别
        $birth_year = substr($str, 6, 4);
        $birth_month = substr($str, 10, 2);
        $birth_day = substr($str, 12, 2);
        if (!checkdate($birth_month, $birth_day, $birth_year)) {
            return false;
        }
        $birthday = $birth_year . "-" . $birth_month . "-" . $birth_day;
        $gender_char = substr($str, -2, 1);
        if ($gender_char % 2 == 0) {
            $gender = 2; //女
        } else {
            $gender = 1; //男
        }

        return [
            'birthday' => $birthday,
            'age' => getAgeByBirthday(strtotime($birthday)),
            'gender' => $gender,
        ];
    }
}

if (!function_exists('regexpChs')) {
    /**
     * 校验字符串是否全部是中文
     * @param $str
     * @return bool
     */
    function regexpChs($str)
    {
        if (preg_match('/^[\x7f-\xff]+$/', $str)) {
            return true; //全是中文
        } else {
            return false; //不全是中文
        }
    }
}

if (!function_exists('regexpPhone')) {
    /**
     * 校验手机号
     * @param $str
     * @return bool|string
     */
    function regexpPhone($str)
    {
        if (preg_match('/^1\d{10}$/ims', $str)) {
            return true; //是手机号
        }
        return '手机号格式错误'; //不是手机号
    }
}

if (!function_exists('getVirRootDir')) {
    /**
     * 获取虚拟目录路径
     * @return bool|string
     */
    function getVirRootDir()
    {
        if (isset($_SERVER['HTTP_X_ORIGINAL_URI'])) {
            $url = $_SERVER['HTTP_X_ORIGINAL_URI'];
            return preg_replace('/\/index\.php.*/m', '', $url);
        } elseif (isset($_SERVER['SCRIPT_NAME'])) {
            $url = $_SERVER['SCRIPT_NAME'];
            $url = substr($url, 0, strripos($url, "/"));
            return $url;
        }
        return '';
    }
}

if (!function_exists('generateSnowFlaskId')) {
    /**
     * 生成雪花算法id
     * @param string $prefix 前缀
     */
    function generateSnowFlaskId($prefix = '')
    {
        return $prefix . (new \Godruoyi\Snowflake\Snowflake)->id();
    }
}

if (!function_exists('getLocalPathFromRemoteUrl')) {
    /**
     * 通过远端url获取本地路径, 必须要是在public下的可访问目录
     * @param $url url
     */
    function getLocalPathFromRemoteUrl($url)
    {
        return preg_replace('/.*\/storage\//ui', public_path('storage'), $url);
    }
}

if (!function_exists('getValueFromArray')) {
    /**
     * 获取数组中的值, 如果不存在则返回默认值
     * @param $key
     * @param $array
     * @param $default
     * @return mixed|string
     */
    function getValueFromArray($key, $array, $default = "")
    {
        if (array_key_exists($key, $array) && $array[$key] !== "") {
            return $array[$key];
        }
        return $default;
    }
}

if (!function_exists('getPublicDirUrl')) {

    function getPublicDirUrl()
    {
        $request_scheme = getValueFromArray("REQUEST_SCHEME", $_SERVER);
        $host = getValueFromArray("HTTP_HOST", $_SERVER);
        return $request_scheme . "://" . $host . WEB_DIR;
    }
}

if (!function_exists('getDiffTime')) {

    //写一个计算两个时间字符串时间差的函数
    function getDiffTime($time1, $time2): float
    {
        $time1 = strtotime($time1);
        $time2 = strtotime($time2);
        $diff = $time2 - $time1;
        $long = floatval($diff) / 3600;
        return round($long, 3);
    }
}



